package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.mess.ArticleEsMess;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-20 14:24
 */
@Component
@Slf4j
public class ArticleEsListener {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void articleEs(String msg){
        if(StringUtils.isNotBlank(msg)){
            ArticleEsMess articleEsMess = JSON.parseObject(msg, ArticleEsMess.class);
            //添加数据请求
            IndexRequest source = new IndexRequest("app_info_article").id(articleEsMess.getId().toString())
                    .source(msg, XContentType.JSON);

            try {
                restHighLevelClient.index(source, RequestOptions.DEFAULT);
            } catch (IOException e) {
                log.error("同步数据到es失败",e);
            }
        }
    }
}
